<?php 
namespace town\model;

use town\dmod\DB;
use town\dmod\Model;

class User extends Model
{

	/**
	 * 用户登录
	 * pass:pwd
	 */
    public function login($name, $pass)
    {
    	$info = $this->link->where('name', $name)->first();
    	
    	// 用户不存在
    	if (empty($info)) {
    		return '用户不存在';
    	}

    	// 密码不对
    	$isRoot = $this->encrypt($pass, $info['salt'], $info['pass']);
    	if ($isRoot !== true) {
	    	return '密码不正确';
    	}

		return $info;
    }


    /**
     * 修改密码
     */
    public function change_passwd($uid, $old, $pass)
    {
    	// $info = $this->link->where('id', $uid)->first();
    	// $auth = $this->encrypt($pass, $info['salt'], $info['pass']);
    	// if ($auth !== true) {
    	// 	return '旧密码不正确';
    	// }
    	// $this->where()
    }


    /**
     * 如果有$salt,则是对比密码->return boolean
     * 没有则是加密->return ['pass':,'salt':]
     */
    private function encrypt($pass, $salt=0, $cipher='')
    {
    	if (empty($salt)) {
    		$salt = mt_rand(10, 99999);
    		$pass = md5($pass.$salt);
    		return [$pass, $salt];
    	}

    	return (md5($pass.$salt) === $cipher);
    }
}